import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAdminStore = defineStore('admin', () => {
  // 状态
  const token = ref(localStorage.getItem('admin_token') || '')
  const adminInfo = ref(null)
  const permissions = ref([])
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const nickname = computed(() => adminInfo.value?.nickname || '')
  
  // 计算属性：检查是否有特定权限
  const hasPermission = computed(() => (permissionCode) => {
    // 系统管理员拥有所有权限
    if (adminInfo.value?.is_super) return true
    
    // 检查权限列表中是否包含所需权限
    return permissions.value.some(p => {
      // 如果当前用户有超级管理员权限（id=1），则拥有除了管理员管理外的所有权限
      if (p.id === 1) {
        return permissionCode !== 'super_admin'
      }
      // 其他情况按具体权限判断
      return p.code === permissionCode
    })
  })
  
  // 方法
  function setToken(newToken) {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('admin_token', newToken)
    } else {
      localStorage.removeItem('admin_token')
    }
  }

  function setAdminInfo(info) {
    if (!info) {
      adminInfo.value = null
      permissions.value = []
      localStorage.removeItem('admin_info')
      return
    }

    // 只保存必要的管理员信息
    const essentialInfo = {
      id: info.id,
      username: info.username,
      nickname: info.nickname,
      avatar_data: info.avatar_data,
      is_super: info.is_super,
      permissions: info.permissions || []
    }
    adminInfo.value = essentialInfo
    permissions.value = Array.isArray(info?.permissions) ? info.permissions : []
    localStorage.setItem('admin_info', JSON.stringify(essentialInfo))
  }

  function clearAdminInfo() {
    token.value = ''
    adminInfo.value = null
    permissions.value = []
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_info')
  }

  // 初始化函数
  function initState() {
    const savedToken = localStorage.getItem('admin_token')
    const savedInfo = localStorage.getItem('admin_info')
    
    if (savedToken) {
      token.value = savedToken
    }
    
    if (savedInfo) {
      try {
        const info = JSON.parse(savedInfo)
        adminInfo.value = info
        permissions.value = Array.isArray(info?.permissions) ? info.permissions : []
      } catch (e) {
        console.error('Failed to parse stored admin info:', e)
      }
    }
  }

  // 初始化
  initState()

  return {
    // 状态
    token,
    adminInfo,
    permissions,
    // 计算属性
    isLoggedIn,
    nickname,
    hasPermission,
    // 方法
    setToken,
    setAdminInfo,
    clearAdminInfo
  }
}) 